package by.bsu.rfe.belianko.euniversity.controller.command;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.ErrorMessages;
import by.bsu.rfe.belianko.euniversity.constants.LoggerMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.dao.IStudentsDAO;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.exceptions.DaoTechnicalException;
import by.bsu.rfe.belianko.euniversity.model.DataBaseLayer;
import by.bsu.rfe.belianko.euniversity.model.Student;

/**
 * Supports administrator actions.
 * 
 * @author Vitali_Belianko
 * 
 */
public class AdminCommand implements Command {

	
	private static final String ADMISSION_STATE = "admissionState";
	private static final String COMPLETE = "complete";
	private static final String ACCEPTED_STUDENT = "acceptedStudent";
	private static final String NOT_APPROVED = "notApproved";
	private static final IStudentsDAO studentsDao = DataBaseLayer.getStudentsDao();
	private static final Logger LOGGER = Logger.getLogger(AdminCommand.class);

	/**
	 * Load list of not approved students. If admission is over load list of
	 * accepted students.
	 * 
	 * @param request
	 * 
	 * @return admin page
	 * @throws CommandException 
	 * 
	 */
	@Override
	public String execute(HttpServletRequest request) throws CommandException {
		LOGGER.debug(LoggerMessages.STARTED_COMMAND);
		List<Student> notApprovedStudentsList = null;
		List<Student> acceptedStudentsList = null;

		try {
			notApprovedStudentsList = studentsDao.getNotApprovedStudents();
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(ErrorMessages.CAN_NOT_GET_NOT_APPROVED_STUDENTS, e);
		}

		request.setAttribute(NOT_APPROVED, notApprovedStudentsList);
		String admissionStateAttribute = (String) request.getSession(true).getAttribute(ADMISSION_STATE);
		if (COMPLETE.equals(admissionStateAttribute)) {

			try {
				acceptedStudentsList = studentsDao.getAcceptedStudents();
			} catch (DaoTechnicalException e) {
				LOGGER.error(e.getMessage());
				throw new CommandException(ErrorMessages.CAN_NOT_GET_ACCEPTED_STUDENTS, e);
			}

			request.getSession(true).setAttribute(ACCEPTED_STUDENT, acceptedStudentsList);

		}

		LOGGER.debug(LoggerMessages.FINISHED_COMMAND);
		return PageNames.ADMIN_PAGE;

	}

}
